import regeneratorRuntime from '../../resource/libs/runtime'
import { websocket_origin, customer_service_phone } from '../../common/config'
import { wxApiPromise, asyncReverseGeocoder } from '../../common/utils'
import service from '../../common/service'

let app = getApp()
let page_config = {
  footer_list: [
    {
      text: '用户中心',
      icon: '/resource/images/user-icon.png'
    },
    {
      text: '联系客服',
      icon: '/resource/images/phone-icon.png'
    }
  ]
}

Page({
  data: {
    ...page_config,
    driver_num: 0, // 候驾司机数
    origin_tip: '正在获取位置信息，请稍后···',
    destination_tip: '您要去哪？',
    origin: '', // 出发地
    destination: '', // 目的地

    coupon_tip: '使用优惠券',
    coupon: '', // 已选的优惠券
    coupon_id: '', // 已选的优惠券 id
    if_coupon_used: false, // 选中的优惠券是否已使用
    coupon_init: false, // 是否已加载优惠券列表
    coupon_list: [],

    money: 0, // 预估价格
    init: false, // 首页是否已初始化完成
    submit_loading: false,
  },

  async onLoad () {
    await this.init()
    wx.onSocketOpen(() => {
      // debug
      app.alert('wss 已打开')
      // debug
      app.global_data.socket_closed = false
      wx.onSocketMessage(async (res) => {
        let res_data = JSON.parse(res.data)
        let { client_id, id, u_id } = res_data.data
        if (client_id) {
          let r = await service.postPromise('gateway/bind', { client_id })
          // debug
          if (r && typeof r !== 'number') {
            app.alert('wss 已建立通讯关系')
          }
          // debug
        }
        if (id) {
          // debug
          app.alert('wss 接收到接单消息')
          // debug
          let r = await wxApiPromise(wx.sendSocketMessage, {
            data: JSON.stringify({ type: "MINIPush", id, u_id })
          })
          if (r) {
            let route = getCurrentPages().pop().route
            let detail_route = 'pages/mine/journey/detail/index'
            let url = `/${detail_route}?id=${id}`
            if (route === detail_route) {
              wx.redirectTo({ url })
            } else {
              wx.navigateTo({ url })
            }
          }
        }
      })
    })
    wx.onSocketClose(() => {
      // debug
      app.alert('wss 已关闭')
      // debug
      app.global_data.socket_closed = true
      if (app.global_data.app_show) {
        wx.connectSocket({
          url: websocket_origin
        })
      }
    })
    // 确保首次连接时 token 是有效的
    wx.connectSocket({
      url: websocket_origin
    })
  },
  onUnload () {
    // 防止因为授权而出现两次加载首页时，执行了 onShow 回调
    app.updateGlobalData({ origin: '', destination: '' })
  },
  async onShow () {
    let { origin, destination, start } = app.global_data
    if (origin && origin !== this.data.origin) {
      this.setData({ origin })
      this.getInfo()
    }
    if (destination !== this.data.destination) {
      this.setData({ destination })
      // 如果未获取价格表，先获取再计算预估价格
      if (!start.length) {
        wx.showLoading({
          title: '数据加载中'
        })
        let res = await service.getPromise('SystemPrice/initPrice/mini')
        wx.hideLoading()
        if (typeof res === 'number') { return }
        if (res) {
          let { interval, start, wait } = res.data
          app.updateGlobalData({ interval, start, wait })
        }
      }
      await app.calPrice()
      let { origin_money, km_money } = app.global_data
      this.setData({ money: origin_money + km_money })
    }
    // 重新获取优惠券列表
    if (this.data.if_coupon_used) {
      this.setData({
        coupon: '',
        coupon_id: '',
        if_coupon_used: false,
        coupon_init: false,
        coupon_list: []
      })
      service.getPromise('tickets/user').then(res => {
        if (!res || typeof res === 'number') { return }
        this.setData({ coupon_list: res.data, coupon_init: true })
      })
    }
  },
  async onPullDownRefresh () {
    await this.init()
    wx.stopPullDownRefresh()
  },

  // 初始化
  async init () {
    // 首先，强制获取用户当前位置的经纬度
    let location = await service.asyncGetLocation(true)
    if (location) {
      let o_location = {
        latitude: location.latitude,
        longitude: location.longitude
      }
      // 然后，根据经纬度获取相关地理信息
      asyncReverseGeocoder({
        location: o_location
      }).then(res => {
        if (res) {
          let { address, address_component } = res.result
          let origin = address
          let o_region = [
            address_component.province,
            address_component.city,
            address_component.district
          ]
          app.updateGlobalData({ origin, o_region, o_location })
          this.setData({ origin })
        }
      })
      // 与此同时，根据经纬度获取业务相关信息
      await this.getInfo(o_location)
    }
  },

  async getInfo (location) {
    wx.showLoading({
      title: '数据加载中'
    })
    location = location || app.global_data.o_location
    let res = await service.getPromise('SystemPrice/initIndex/mini', {
      lat: location.latitude,
      lng: location.longitude
    })
    wx.hideLoading()
    if (typeof res === 'number') { return }
    if (res) {
      let { drivers, interval, tickets } = res.data
      app.updateGlobalData({ interval })
      await app.calPrice()
      let { origin_money, km_money } = app.global_data
      this.setData({
        init: true,
        driver_num: drivers,
        money: origin_money + km_money,
        coupon_list: tickets,
        coupon_tip: '使用优惠券',
        coupon_init: true
      })
    }
  },

  async submit () {
    if (!app.global_data.phone) {
      wx.navigateTo({
        url: '/pages/mine/index'
      })
    } else if (!this.data.submit_loading) {
      this.setData({ submit_loading: true })
      let t_id = this.data.coupon_id
      let { origin, o_location, destination, d_location } = app.global_data
      let res = await service.postPromise('order/mini/save', {
        start: origin,
        start_lat: o_location.latitude,
        start_lng: o_location.longitude,
        end: destination,
        end_lat: d_location.latitude,
        end_lng: d_location.longitude,
        t_id
      })
      this.setData({ submit_loading: false })
      if (!res) { return }
      if (typeof res === 'number') {
        await wxApiPromise(wx.showModal, {
          title: '下单失败',
          showCancel: false
        })
        return
      }
      if (t_id) {
        this.setData({ if_coupon_used: true })
      }
      wx.navigateTo({
        url: '/pages/mine/journey/detail/index?id=' + res.data.id
      })
    }
  },

  originTap() {
    wx.navigateTo({
      url: '/pages/site/index?type=origin'
    })
  },
  destinationTap() {
    wx.navigateTo({
      url: '/pages/site/index?type=destination'
    })
  },
  async couponTap() {
    let coupon_list = this.data.coupon_list
    if (coupon_list.length === 0) {
      this.setData({
        coupon_tip: '暂无优惠券'
      })
      return
    }
    let list = []
    coupon_list.forEach(item => {
      list.push(item.money + '元' + item.name)
    })
    list.push('不使用优惠券')
    let res = await wxApiPromise(wx.showActionSheet, {
      itemList: list
    })
    if (res) {
      let { tapIndex } = res
      let if_last_index = tapIndex === list.length - 1
      this.setData({
        coupon: if_last_index ? '' : list[tapIndex],
        coupon_id: if_last_index ? '' : coupon_list[tapIndex].id
      })
    }
  },
  questionTap() {
    wx.navigateTo({
      url: '/pages/question/index'
    })
  },
  footerTap ({ currentTarget }) {
    let index = currentTarget.dataset.index
    if (index === 0) {
      wx.navigateTo({
        url: '/pages/mine/index'
      })
    } else {
      wx.showActionSheet({
        itemList: customer_service_phone,
        success({ tapIndex }) {
          wx.makePhoneCall({
            phoneNumber: customer_service_phone[tapIndex]
          })
        }
      })
    }
  }
})